package tksTcp

import (
	"net"
	. "tksLog"
)

type clientCallback func(net.Conn, uint32, uint32, []byte)

var client *TksTcpConn
var clientCmds map[uint32]clientCallback

func init() {
	clientCmds = make(map[uint32]clientCallback)
}

func clientInit(conn net.Conn) {
	Debug("new connnect from %s", conn.RemoteAddr().String())
}

func clientReceive(conn net.Conn, cmd uint32, from uint32, to uint32, data []byte) {
	if cb, ok := clientCmds[cmd]; ok {
		cb(conn, from, to, data)
	}
}

func clientClose(conn net.Conn) {
	Debug("client close connect from %s\n", conn.RemoteAddr().String())
}

func RegisterCmd(cmd uint32, cb clientCallback) {
	_, ok := clientCmds[cmd]
	if ok {
		return
	} else {
		clientCmds[cmd] = cb
	}
}

func NewServer(port string) error {
	client = new(TksTcpConn)
	err := client.CreateServer(port, clientInit, clientReceive, clientClose)
	if err != nil {
		return err
	}
	return nil
}
